import React, { useState, useEffect } from 'react';
import { getTest1, getTest2, getTest3 } from '../../api/promsie';
import { ResponseData } from '../../types/common';
import { IAllSettled, IPromiseData } from '../../types/Ipromise';
import './com.css';

export default function Complicated(): JSX.Element {
  const [res, setRes] = useState<IAllSettled<ResponseData<IPromiseData>>[]>();
  const [isLoading, setIsLoading] = useState(false);
  // 处理并发请求
  async function complicated(): Promise<
    IAllSettled<ResponseData<IPromiseData>>[]
  > {
    // 同时发送的请求  any all  allSellected
    // any  all race allSettled
    // race
    return await Promise.allSettled([getTest1(1), getTest2(2), getTest3(3)]);
  }

  useEffect(() => {
    async function sendRequest(): Promise<any> {
      const start = new Date().getTime();
      setIsLoading(true);
      const result = await complicated();
      setRes(result);
      const end = new Date().getTime();
      console.log(end - start);
      setTimeout(() => setIsLoading(false), 300);
    }
    sendRequest();
  }, []);
  return (
    // fragemnt : Fragment 最终不会编译成 HTML 标签，而是作为 React 组件的一部分渲染。
    <>
      <ul>
        {res?.map((item, index) => (
          <li key={index}>
            {item.status === 'fulfilled' && (
              <span>fulfilled : {item.value?.data.receiveId}</span>
            )}
            {item.status === 'rejected' && (
              <span>rejected : {JSON.stringify(item.reason.message)}</span>
            )}
          </li>
        ))}
      </ul>

      <div>
        {isLoading && (
          <img
            className="loading"
            src="https://cdn.jsdelivr.net/gh/IceRain-mvc/cdn/img/loading.png"
            alt="loading"
          />
        )}
      </div>
    </>
  );
}
